let express = require('express');
let app = express();
let sliders = require('./mock/sliders');
let lessons = require('./mock/lessons');
let bodyParser = require('body-parser');
let session = require('express-session');
let users = [];

app.use(bodyParser.json())

app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'zeihang'
}))

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', "http://localhost:8080");
    res.setHeader('Access-Control-Allow-Headers', "Content-Type");
    res.setHeader('Access-Control-Allow-Methods', "GET,POST,OPTIONS");
    res.setHeader('Access-Control-Allow-Credentials', true);
    if (req.method == 'OPTIONS') {
        res.end("");
    } else {
        next();
    }
})

app.get('/api/sliders', function (req, res) {
    res.json({
        code: 0,//0表示成功 非0表示失败
        data: sliders
    });
});

app.get('/api/lessons/:category', function (req, res) {
    let currentLessons = JSON.parse(JSON.stringify(lessons));
    let category = req.params.category;//当前分类的名称
    let offset = isNaN(req.query.offset) ? 0 : parseInt(req.query.offset);//偏移量
    let limit = isNaN(req.query.limit) ? 5 : parseInt(req.query.limit);//每页条数
    if (category && category != 'all') {
        currentLessons = currentLessons.filter(item => item.category == category);
    }
    //1=0,5 2=5,5+5=10  取得当前页的数据
    let list = currentLessons.slice(offset, offset + limit);
    let hasMore = currentLessons.length > offset + limit;//后面是否还有更多
    setTimeout(function () {
        res.json({
            code: 0,
            data: { list, hasMore }
        });
    }, 1000);
});

app.post('/api/reg', function (req, res) {
    let user = req.body;
    
    user.id = users.length > 0 ? users[users.length - 1].id + 1 : 1;
    users.push(user);
    console.log(users);
    res.json({
        code: 0,
        data: {
            user,
            success: '注册成功'
        }
    })
})

app.post('/api/login', function (req, res) {
    let user = users.find(item => item.username == req.body.username && item.password == req.body.password);
    if (user) {
        req.session.user = user;
        res.json({
            code: 0,
            data: {
                user,
                success: '登陆成功'
            }
        });
    } else {
        res.json({
            code: 1,
            data: {
                error: '登陆失败'
            }
        });
    }
});

app.listen(3000, () => {
    console.log('启动在3000端口')
});

